<template>
  <view class="time-popup" v-cloak>
    <view class="popup-main">
      <view class="main-card">
        <view class="main-title">预约项目（可不选）</view>
        <view class="main-project">
          <view class="project-item" :class="item.id == invitationParams.appointmentItemCategoryId?'active':''" v-for="(item) in popupCate" :key="item.id" @click="invitationParams.appointmentItemCategoryId = item.id">{{item.name}}</view>
        </view>
      </view>
      <view class="main-card">
        <view class="main-title">预约医生</view>
        <view class="main-doctor">
          <view class="doctor-item" :class="invitationParams.doctorStaffId == item.id?'active':''" v-for="(item) in doctorList" :key="idx" @click="invitationParams.doctorStaffId = item.id">
            <image :src="item.avatar || '../../static/gray.jpg'" mode="aspectFill" class="img"></image>
            <image src="@/static/check-on.png" v-show="item.id == invitationParams.doctorStaffId" mode="aspectFill" class="icon"></image>
            <view class="h2">{{item.realName}}</view>
          </view>
          <view class="doctor-item" :class="invitationParams.doctorStaffId == '0'?'active':''" @click="invitationParams.doctorStaffId = 0">
            <image src="@/static/doctor-default.png" mode="aspectFill" class="img"></image>
            <image src="@/static/check-on.png" v-show="invitationParams.doctorStaffId == '0'" mode="aspectFill" class="icon"></image>
            <view class="h2">到店分配</view>
          </view>
        </view>
      </view>
      <view class="main-card">
        <view class="main-title">到店时间 <span style="color: #f00; margin-left: 8rpx;">*</span> <image src="@/static/date-icon.png" class="date-icon" mode="aspectFill"></image></view>
        <view class="main-tabs not-bar">
          <view class="tabs-item" :class="idx == invitationParams.curDate?'active':''" v-for="(item,idx) in dateList" :key="item.date" @click="handleChangeDate(idx)">
            <view class="item-h2">{{item.dateStr}}</view>
            <view>{{format(item.date)}}</view>
          </view>
        </view>
        <view class="main-time" v-if="dateList[invitationParams.curDate]">
          <view class="time-item" :class="{active:idx == invitationParams.curTime,disabled: isSlotDisabled(item)}" v-for="(item,idx) in dateList[invitationParams.curDate].timeList" :key="idx" @click="handleChangeTime(idx)">{{item.startTime}}-{{item.endTime}}</view>
        </view>
      </view>
      <view class="main-item main-card">
        <view class="item-label">联系方式 <span style="color: #f00; margin-left: 8rpx;">*</span> <view class="label-span">用于门店跟您确认到店时间</view></view>
        <input class="input" type="text" v-model="invitationParams.mobile" placeholder="联系方式" />
      </view>
      <view class="main-item main-card">
        <view class="item-label">备注</view>
        <input class="input" type="text" v-model="invitationParams.notes" placeholder="选填，可备注说明" />
      </view>
    </view>
    <view class="popup-footer">
      <view class="button" @click="handleSubmit()">{{invitationId?'修改预约':'立即预约'}}</view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        user:uni.getStorageSync('user') || {},
        orderId:undefined,
        dateList:[],
        timeList:['08:00-10:00','10:00-12:00','14:00-16:00','16:00-18:00'],
        invitationParams:{
          curDate:0,
          curTime:0,
          doctorStaffId:0,
          appointmentItemCategoryId:null,
          notes:'',
          mobile:uni.getStorageSync('user').mobile
        },
        selectStore:{},
        doctorList:[],
        popupCate:[],
        invitationId:null
      };
    },
    onLoad(ops) {
      this.invitationId = ops.invitationId || null
      this.selectStore = uni.getStorageSync('selectStore')
      this.$get(`/merchant/v1/org/selectBusinessHours/${this.selectStore.id}`).then(res=>{
        if(res.code == '1'){
          this.dateList = res.content
          const currentHour = new Date().getHours();
          if(currentHour > 18){
            this.invitationParams.curDate = 1
          }
        }
      })
      if(ops.id){
        this.invitationParams.doctorStaffId = ops.id
      }
      if(ops.orderId){
        this.orderId = ops.orderId
      }
      this._initData()
      if(ops.invitationId){
        this.$get('/yahe/appointment/getInfo',{
          id:ops.invitationId
        },'1').then(res=>{
          if(res.code == '1'){
            const {content} = res
            this.invitationParams = {
              ...this.invitationParams,
              mobile:content.appointmentPhone,
              notes:content.notes,
              id:ops.invitationId,
              doctorStaffId:content.appointmentDoctorId,
              appointmentItemCategoryId:content.appointmentProjectId
            }
          }
        })
      }
    },
    methods:{
      format(dateStr){
        const date = new Date(dateStr);
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${month}-${day}`;
      },
      isSlotDisabled(slot) {
        if (!this.isToday(this.dateList[this.invitationParams.curDate].date)) return false; // 非今日不禁用
        const now = new Date();
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        const [start, end] = [slot.startTime,slot.endTime]
        const [startHour, startMin] = start.split(':').map(Number);
        const [endHour, endMin] = end.split(':').map(Number);
        const currentTotalMinutes = currentHour * 60 + currentMinute;
        const startTotalMinutes = startHour * 60 + startMin;
        const endTotalMinutes = endHour * 60 + endMin;
        return currentTotalMinutes > endTotalMinutes;
      },
      isToday(dateStr) {
        const today = new Date();
        const targetDate = new Date(dateStr);
        return (
            targetDate.getFullYear() == today.getFullYear() &&
            targetDate.getMonth() == today.getMonth() &&
            targetDate.getDate() == today.getDate()
        );
      },
      handleChangeDate(idx){
        this.invitationParams.curDate = idx;this.invitationParams.curTime = 0
        if(idx == 0 && this.isSlotDisabled(this.dateList[this.invitationParams.curDate].timeList[idx])) this.invitationParams.curTime = undefined;
      },
      handleChangeTime(idx){
        if (this.isSlotDisabled(this.dateList[this.invitationParams.curDate].timeList[idx])) return;
        this.invitationParams.curTime = idx
      },
      handleSubmit(){
        if(!(this.invitationParams.curTime >= 0)){
          this.$toast('请先选择到店时间')
          return;
        }
        let date = this.dateList[this.invitationParams.curDate].date
        let time = this.dateList[this.invitationParams.curDate].timeList[this.invitationParams.curTime]
        const year = new Date().getFullYear()
        const data = {
          ...this.invitationParams,
          merchantId:this.selectStore.merchantId,
          orgId:this.selectStore.id,
          appointmentStartTime:`${date} ${time.startTime}:00`,
          appointmentEndTime:`${date} ${time.endTime}:00`
        }
        uni.showModal({
          title:data.id?'确定修改预约?':'确定立即预约?',
          success:result=>{
            if(result.confirm){
              uni.showLoading({
                title:'加载中...'
              })
              if(data.id){  ///  修改
                this.$post('/yahe/appointment/update',data,'1').then(res=>{
                  if(res.code == '1'){
                    this.$toast('提交成功','success')
                    setTimeout(()=>{
                      uni.navigateTo({
                        url:`/doctorPackage/invitation-detail?id=${data.id}`
                      })
                    },1000)
                  }else{
                    this.$toast(res.message)
                  }
                })
                return;
              }
              if(this.orderId){
                Object.assign(data,{
                  orderId:this.orderId
                })
              }
              this.$post('/yahe/appointment/save',data,'1').then(res=>{
                if(res.code == '1'){
                  this.$toast('提交成功','success')
                  setTimeout(()=>{
                    if(this.orderId){
                      this.$get('/product/yahe/mp/appointment/update',{
                        appointmentId:res.content || undefined,
                        orderId:this.orderId
                      }).then(res=>{
                        if(res.code == '1'){
                          uni.redirectTo({
                            url:`/minePackage/order-detail?id=${this.orderId}`
                          })
                        }else{
                          this.$toast(res.message)
                        }
                      })
                      return;
                    }
                    uni.navigateTo({
                      url:`/doctorPackage/invitation-success?id=${res.content}`
                    })
                  },1000)
                }else{
                  this.$toast(res.message)
                }
              })
            }
          }
        })
      },
      _initData(){
        this.selectStore = uni.getStorageSync('selectStore')
        if(this.selectStore){
          this.$get('/merchant/v1/staff',{orgId:this.selectStore.id}).then(res=>{
            this.doctorList = res.content || []
          })
          this.$get(`/product/app/productReleaseAppGroup/selectProductReleaseGroup/${this.selectStore.merchantId}`).then(res=>{
            if(res.code == '1'){
              this.popupCate = res.content
            }
          })
        }
      },
    }
  }
</script>

<style lang="less">

    .time-popup{
      min-height: 100vh;
      background: var(--page-bg);
      border-radius: 20rpx 20rpx 0 0;
      padding: 24rpx;
      box-sizing: border-box;
      .popup-header{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 24rpx;
        h2{
          font-size: 28rpx;
          color: var(--title-color);
        }
      }
      .popup-main{
        .main-card{
          padding: 28rpx 24rpx;
          background: #fff;
          border-radius: 20rpx;
          margin-bottom: 20rpx;
        }
        .main-title{
          font-size: 28rpx;
          margin-bottom: 6rpx;
          color: var(--title-color);
          display: flex;
          align-items: center;
          .date-icon{
            width: 32rpx;
            height: 32rpx;
            margin-left: auto;
          }
        }
        .main-doctor{
          display: flex;
          align-items: center;
          .doctor-item{
            margin-right: 20rpx;
            width: 114rpx;
            border-radius: 8rpx;
            overflow: hidden;
            border: 2rpx solid transparent;
            position: relative;
            &.active{
              border-color: var(--theme-color);
            }
            .img{
              width: 114rpx;
              height: 114rpx;
              display: block
            }
            .icon{
              position: absolute;
              right: 0;
              top: 0;
              width: 30rpx;
              height: 30rpx;
            }
            .h2{
              font-size: 22rpx;
              color: var(--title-color);
              line-height: 38rpx;
              text-align: center;
            }
          }
        }
        .main-project{
          display: flex;
          flex-wrap: wrap;
          .project-item{
            width: 150rpx;
            line-height: 60rpx;
            text-align: center;
            background: var(--page-bg);
            margin-right: 18rpx;
            margin-top: 18rpx;
            font-size: 24rpx;
            border-radius: 60rpx;
            color: #6D6D6D;
            &:nth-child(4n){
              margin-right: 0;
            }
            &.active{
              background: var(--theme-color);
              color: #fff;
            }
          }
        }
        .main-tabs{
          display: flex;
          flex-wrap: nowrap;
          overflow-x: auto;
          align-items: center;
          margin: 18rpx 0 6rpx;
          .tabs-item{
            width: 90rpx;
            border-bottom: 4rpx solid transparent;
            margin-right: 10rpx;
            padding-bottom: 8rpx;
            color: #B0B0B0;
            white-space: nowrap;
            text-align: center;
            font-size: 22rpx;
            flex-shrink: 0;
            .item-h2{
              color: #6D6D6D;
              font-size: 26rpx;
            }
            &.active{
              border-bottom: 4rpx solid var(--theme-color);
              color: var(--theme-color);
              .item-h2{
                color: var(--theme-color);
              }
            }
          }
        }
        .main-time{
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .time-item{
            width: 49%;
            line-height: 60rpx;
            border-radius: 60rpx;
            text-align: center;
            background: var(--page-bg);
            margin-top: 18rpx;
            font-size: 24rpx;
            color: #6D6D6D;
            &.active{
              background: var(--theme-color);
              color: #fff;
            }
            &.disabled{
              background: #999!important;
              color: #6D6D6D!important;
              opacity: .5;
            }
          }
        }
        
        .main-item{
          display: flex;
          align-items: center;
          .item-label{
            font-size: 28rpx;
            color: var(--title-color);
            margin-right: auto;
            .label-span{
              color: #B0B0B0;
              font-size: 22rpx;
            }
          }
          .item-info{
            display: flex;
            align-items: center;
            justify-content: right;
            font-size: 28rpx;
            color: var(--title-color);
          }
          .input{
            text-align: right;
            font-size: 28rpx;
            color: #6D6D6D;
          }
        }
      } //  popup-main end
      
      .popup-footer{
        margin-top: 24rpx;
        padding: 14rpx 0 0;
        .button{
          line-height: 72rpx;
          font-size: 28rpx;
          background: linear-gradient( 90deg, #29D8C6 0%, #10BEAF 100%);
          text-align: center;
          border-radius: 72rpx;
          color: #fff;
        }
      }
    }  // time-popup end
</style>